<!--
@description    表格展示
@author         秦俊强
@email          458112865@qq.com
@create         2021-06-07
-->

<template>
    <div class="content">
        <el-table :data="tableData" style="width: 100%;" max-height="600"
                  row-key="id" border highlight-current-row
                  :header-row-style=backgroundColor
                  :header-cell-style=backgroundColor
                  :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
                  id="rebateSetTable"
                  >
            <template v-for="(itemHead, index) in tableHead">
                <el-table-column v-if="itemHead.prop==='totalPeople'|| (itemHead.prop!==''&&Number(itemHead.prop)>=0)"
                                 :key="index" :label="itemHead.label" :property="itemHead.prop"
                                 :align="index > 1 ? 'right' : ''"
                                 sortable
                                 :width="index === 0 ? '45px' : ''"
                                 >
                    <template slot-scope="scope">
                        <div v-if="isArray(scope.row[scope.column.property])&&scope.row[scope.column.property].length>1"  class="item-value" :style="{backgroundColor:getItemBackgroudColor(scope.row[scope.column.property])}">
                            <div v-for="(item, ind) in scope.row[scope.column.property]"
                                 :key="ind" :class="[ind !== 0? 'item-value-detail':'item-value-head']" >
                                <template v-if="item.toString().indexOf('人') > -1">
                                    <el-popover
                                            popper-class="popoverClass"
                                            placement="top"
                                            trigger="click">
                                        <user-dialog
                                            :userDialogData="userDialogData"></user-dialog>
                                        <el-button class="stepUser" type="text" slot="reference" @click="selCurrentItem(item,index,itemHead,tableHead,scope)">{{ item }} </el-button>
                                    </el-popover>
                                </template>
                                <template v-else >
                                    <span>{{ item }}</span>
                                </template>
                            </div>
                            <div class="fix-height"></div>
                        </div>
                        <template v-else >
                            <template v-if="scope.row[scope.column.property].toString().indexOf('人') > -1">
                                <el-popover
                                        popper-class="popoverClass"
                                        placement="top"
                                        trigger="click">
                                    <user-dialog
                                            :userDialogData="userDialogData"></user-dialog>
                                    <el-button class="stepUser" type="text" slot="reference" @click="selCurrentItem(null,null,itemHead,tableHead,scope)">{{ scope.row[scope.column.property] }}</el-button>
                                </el-popover>
                            </template>
                            <template v-else>
                                <template v-if="isArray(scope.row[scope.column.property])">
                                    <div class="item-value item-value-center"   :style="{backgroundColor:getItemBackgroudColor(scope.row[scope.column.property][0])}">
                                        {{ scope.row[scope.column.property][0] }}
                                    </div>
                                </template>
                                <template v-else>
                                    <div class="item-value item-value-center"   :style="{backgroundColor:getItemBackgroudColor(scope.row[scope.column.property])}">
                                        {{ scope.row[scope.column.property] }}
                                    </div>
                                </template>
                            </template>
                        </template>
                    </template>
                </el-table-column>

                <el-table-column v-else
                                 :header-row-style=backgroundColor
                                 :key="index" :label="itemHead.label" :property="itemHead.prop"
                                 :align="index > 1 ? 'right' : ''"
                                 :width="index === 0 ? '45px' : ''">
                    <template slot-scope="scope">
                        <div v-if="isArray(scope.row[scope.column.property])" >
                            <div v-for="(item, ind) in scope.row[scope.column.property]"
                                 :key="ind" :style="{ color: ind === 1 ? '#0AA372' : ''}">{{ item }}
                            </div>
                        </div>

                        <div v-else >{{ scope.row[scope.column.property] }}</div>
                    </template>
                </el-table-column>
            </template>

        </el-table>
    </div>
</template>


<script>
    import FileSaver from 'file-saver'
    import XLSX from 'xlsx'
    /*用户弹框跳转组件*/
    import userDialog from "./userDialog";

    export default {
        name: 'table-funnel',
        components: {
            userDialog
        },
        props: {
            timeType: {
                type: String,
                default :'天'
            },
            retainedReportResData: {
                type: Object,
                default: null
            },
            //用来获取表头信息
            byXXXReadtabsBodyParams: {
                type: Array,
                default: []
            },
            //点击表格中人数触发的弹框
            userDialogData:{
                type:Object,
                default: {}
            }
        },

        data() {
            return {
                backgroundColor: {background: '#f7f9fa'},
                tableHead: [],
                tableData: [],

                /*是否按照某种或多种类型进行分组*/
                isByValues: false,
            }
        },

        created() {
            let t = this;
            t.tableHead = [];
            t.tableData = [];

            t.initTabHead();
            t.$watch('retainedReportResData', () => {
                // console.log('funnelReportResData = ', t.funnelReportResData);
                // console.log('funnelDetail = ', t.funnelReportResData.funnelDetail);

                t.tableHead = [];
                t.tableData = [];

                t.initTabHead();
            });
        },

        methods: {
            exportExcel () {
                /* generate workbook object from table */
                let wb = XLSX.utils.table_to_book(document.querySelector('#rebateSetTable'));
                /* get binary string as output */
                let wbout = XLSX.write(wb, { bookType: 'xlsx', bookSST: true, type: 'array' });
                try {
                    FileSaver.saveAs(new Blob([wbout], { type: 'application/octet-stream' }), '计算结果.xlsx');
                } catch (e)
                {
                    if (typeof console !== 'undefined')
                        console.log(e, wbout)
                }
                return wbout
            },
            selCurrentItem(item,index,itemHead,tableHead,scope) {
                let sliceInterval = "";
                let sliceByValues = [];
                let sliceDate = "";

                /*第几列*/
                if (itemHead.prop !== "totalPeople") {
                    sliceInterval = itemHead.prop;
                }

                /*选择的时间*/
                if (this.isByValues === true) {
                    sliceDate = scope.row.title;
                }else{
                    sliceDate = scope.row.byValue;
                }
                if (sliceDate === undefined||sliceDate==="总体") {
                    sliceDate = "";
                }

                // /*按什么进行分组*/
                if (this.retainedReportResData.byFields.length !== 0) {
                    let index = scope.$index + 1;
                    let mainIndex = 0;
                    for (let i = 0; i < this.tableData.length; i++) {
                        index = index - this.tableData[i].children.length - 1
                        if (index <= 0) {
                            mainIndex = i;
                            break
                        }
                    }
                    for (let i = 0; i < this.retainedReportResData.byFields.length; i++) {
                        sliceByValues.push(this.tableData[mainIndex][this.retainedReportResData.byFields[i]]);
                    }
                }

                this.userDialogData.sliceInterval = sliceInterval;
                this.userDialogData.sliceDate = sliceDate;
                this.userDialogData.sliceByValues = sliceByValues;
            },
            getItemBackgroudColor(item) {
                let precent = 0;
                let color = "";
                if (this.isArray(item)) {
                    if (item.length !== 3) {
                        for (let i = 0; i < item.length; i++) {
                            if (item[i].indexOf("%")>-1) {
                                precent = item[i].substring(0,item[i].length-1);
                                break
                            }
                        }
                    }else{
                        precent = item[2].substring(0,item[2].length-1);
                    }
                }else{
                    let str = item + "";
                    if (str.indexOf("%")>-1) {
                        precent = item.substring(0,item.length-1);
                    }
                }

                precent = Number(precent);

                if (precent === 0) {
                    color = "#FFFFFF";
                } else if (precent < 10) {
                    color = "#F6FAFD";
                } else if (precent < 20) {
                    color = "#EBF4FB";
                } else if (precent < 30) {
                    color = "#E1EDF8";
                } else if (precent < 40) {
                    color = "#D6E7F5";
                } else if (precent < 50) {
                    color = "#CBE0F2";
                } else if (precent < 60) {
                    color = "#C0DAEF";
                } else if (precent < 70) {
                    color = "#B4D3EC";
                } else if (precent < 80) {
                    color = "#A8CDE9";
                } else if (precent < 90) {
                    color = "#9BC6E6";
                } else if (precent < 100){
                    color = "#9BC6E6";
                }else{
                    color = "#9BC6E6";
                }
                return color;
            },
            /* 判断是否是数组 */
            isArray: (a) => {
                return (Object.prototype.toString.call(a) === '[object Array]');
            },


            initTabHead() {
                let t = this;
                if (t.retainedReportResData === null || t.retainedReportResData.byFields === undefined) {
                    return;
                }
                if (t.retainedReportResData.byFields.length === 0) {
                    this.isByValues = false;
                    t.initTotalHead();
                    t.initTabTotalData();
                } else {
                    this.isByValues = true;
                    t.initValueHead();
                    t.initTabValueData();
                }


            },
            //含有属性值的报文
            initValueHead() {
                let t = this;
                let dates = t.retainedReportResData.byFields;
                for (let i = 0; i < dates.length; i++) {
                    if (i === 0) {
                        t.tableHead.push({prop: '', label: ''});              // 折叠展开箭头
                        t.tableHead.push({prop: dates[0], label: this.getTabHeadCname(dates[0])});
                    } else {
                        t.tableHead.push({prop: dates[i], label: this.getTabHeadCname(dates[i])});
                    }
                }
                t.tableHead.push({prop: 'totalPeople', label: "总人数"});
                if (t.retainedReportResData.rows.length !== 0) {
                    for (let i = 0; i < t.retainedReportResData.rows[0].cells.length; i++) {
                        t.tableHead.push({prop: '' + i, label: '第' + i + this.timeType});
                    }
                }
            },
            initTotalHead() {
                let t = this;
                t.tableHead.push({prop: '', label: ''});
                t.tableHead.push({prop: 'byValue', label: '总体'});
                t.tableHead.push({prop: 'totalPeople', label: '总人数'});
                if (t.retainedReportResData.rows.length !== 0) {
                    for (let i = 0; i < t.retainedReportResData.rows[0].cells.length; i++) {
                        t.tableHead.push({prop: '' + i, label: '第' + i + this.timeType});
                    }
                }
            },
            getTabHeadCname(head) {
                let heads = head.split(".")
                if (heads[0] === 'event') {
                    for (let i = 0; i < this.byXXXReadtabsBodyParams[0].list.length; i++) {
                        if (heads[2] === this.byXXXReadtabsBodyParams[0].list[i].name) {
                            return this.byXXXReadtabsBodyParams[0].list[i].cname;
                        }
                    }
                } else if (heads[0] === 'user') {
                    for (let i = 0; i < this.byXXXReadtabsBodyParams[1].list.length; i++) {
                        if (heads[2] === this.byXXXReadtabsBodyParams[1].list[i].name) {
                            return this.byXXXReadtabsBodyParams[1].list[i].cname;
                        }
                    }
                }
            },
            /* 初始化表身数据 含有属性数值*/
            initTabValueData() {
                let t = this;
                // 表身数据 byValues 的 length 表示一共有多少主行数

                for (let i = 0; i < t.retainedReportResData.rows.length; i++) {
                    let tabTem = t.getTabTem(true);

                    //主行数
                    let itemEvent = t.retainedReportResData.rows[i];
                    t.getRowDataByValue(tabTem, itemEvent.cells, i);
                    for (let j = 0; j < itemEvent.subRows.length; j++) {
                        let cTabTem = t.getTabTem();
                        cTabTem.title = itemEvent.subRows[j].byValue;
                        cTabTem['totalPeople'] = itemEvent.subRows[j].totalPeople + '人';
                        if (itemEvent.subRows[j].cells === undefined) {
                            continue
                        }
                        tabTem.children.push(t.getRowDataByValue(cTabTem, itemEvent.subRows[j].cells, i, true, itemEvent.subRows[j].byValue));
                    }

                    tabTem['totalPeople'] = t.retainedReportResData.rows[i].totalPeople + '人';
                    t.tableData.push(tabTem);
                }
            },
            /* 初始化表身数据 不含属性值(选择总体)*/
            initTabTotalData() {
                let t = this;
                // 表身数据 只有一个主行
                let tabTem = t.getTabTem(true);


                //主行数
                let itemEvent = t.retainedReportResData.rows[0];
                t.getRowDataByTotal(tabTem, itemEvent.cells);


                for (let j = 1; j < t.retainedReportResData.rows.length; j++) {
                    let cTabTem = t.getTabTem();
                    cTabTem.byValue = t.retainedReportResData.rows[j].byValue;
                    cTabTem['totalPeople'] = t.retainedReportResData.rows[j].totalPeople + '人';
                    tabTem.children.push(t.getRowDataByTotal(cTabTem, t.retainedReportResData.rows[j].cells, j));
                }

                t.tableData.push(tabTem);

            },
            /* 返回数组字符串 例：['a', null] => 'a, null' */
            getByValuesListStr(arr) {
                let str = '';

                for (let i = 0; i < arr.length; i++) {
                    let val = arr[i];
                    str = str + val + ((i === arr.length - 1) ? '' : ', ');
                }

                return str;
            },
            /* 返回表格行 选择总数时 */
            getRowDataByTotal(resData, overview, parentIndex) {
                let t = this;
                if (parentIndex === undefined) {
                    resData['byValue'] = '总体';
                    resData['totalPeople'] = t.retainedReportResData.rows[0].totalPeople + "人";
                    for (let i = 0; i < overview.length; i++) {
                        resData['' + i] = overview[i].percent + "%";
                    }
                } else {
                    for (let i = 0; i < overview.length; i++) {
                        if (overview[i].values[0] !== undefined) {
                            resData['' + i] = [overview[i].people + '人',overview[i].values[0], overview[i].percent + "%"];
                        }else{
                            resData['' + i] = [overview[i].people + '人',overview[i].percent + "%"];
                        }

                    }
                    return resData;
                }

            },

            /* 返回表格行 选择非总数时 */
            getRowDataByValue(resData, overview, parentIndex, isSub, byValue) {
                let t = this;

                for (let i = 0; i < t.retainedReportResData.byFields.length; i++) {
                    if (isSub !== true) {
                        let title = t.retainedReportResData.byFields[i];
                        resData[title] = t.retainedReportResData.rows[parentIndex].byValues[i];
                    } else {
                        if (i === t.retainedReportResData.byFields.length - 1) {
                            let title = t.retainedReportResData.byFields[i];
                            resData[title] = byValue;
                        }
                    }
                }

                for (let i = 0; i < overview.length; i++) {
                    let item = overview[i];
                    if (isSub === true) {
                        resData[i] = [item.people + '人', item.percent + '%'];
                    } else {
                        resData[i] = [item.percent + '%'];
                    }
                }
                return resData;
            },
            /* 返回表身数据模板 */
            getTabTem(b) {
                let tabTem = {};

                for (let i = 0; i < this.tableHead.length; i++) {
                    let item = this.tableHead[i];

                    // 标识唯一 id，方便折叠展开，和点击高亮行
                    tabTem['id'] = Number(Math.random().toString().substr(3, 10) + Date.now()).toString(36);

                    if (item.prop) {
                        tabTem[item.prop] = '';
                    }

                    if (b) {
                        tabTem['children'] = [];
                    }
                }

                return tabTem;
            },

        },
        watch: {}
    }
</script>

<style>
    .popoverClass {
        padding: 0px !important;
        background: #000000;
    }
    .popper__arrow::after{
        border-top-color: #000000 !important;
    }
</style>
<style scoped lang="scss">

    /deep/.el-table tbody tr:hover>td {
        background-color:#ffffff !important
    }

    /deep/.el-table__body tr.current-row>td{
        background-color: #ffffff !important;
    }

    .item-value{
        text-align: center;
        height: 80px;
        .item-value-detail{
            height: 14px;
            line-height: 14px;
            font-size: 6px;
            margin-bottom: 2px;
        }
        .item-value-head{
            margin-bottom: 3px;
        }
    }
    .item-value-center{
        line-height: 80px;
    }
    ::v-deep .el-table tbody td {
        padding: 5px 0;
    }

    .fix-height{
        height: 10px;
    }
</style>
